

const initStr = 'babaxc'

function findLastIndex(str, c) {
    const _str = str.split('').reverse()
    const _index = _str.findIndex(item => item === c)
    return _index === -1 ? null : _str.length - 1 - _index;
}

function match(string) {
  let state = start;
  for(let c of string) {
      state = state(c, initStr);
  }
  return state === end
}

function start(c) {
    if (c === initStr[0]) 
      return KMP;
    else 
      return start
}

function end(c) {
    return end
}


function KMP(c, initStr) {
    if (this.index === undefined) {
      this.index = 1;
    }
    if (c===initStr[this.index]) {
        if (this.index === initStr.length-1) {
            return end
        }
        this.index++
        this.beforeWord = c;
        return KMP
    } else {
        const str = initStr.slice(0, this.index - 1)
        if (str && str.includes(this.beforeWord)) {
            const _index = findLastIndex(str, this.beforeWord)
            this.index = _index;
            return KMP(c, initStr)
        }
        this.index = 0;
        return start(c)
    }
}
console.log(match("xcsxcbabababaxc"))